import { DirectiveBinding } from 'vue'

// 键是弱引用，这意味着如果对象的唯一引用在 WeakMap 中，那么这个对象可以被垃圾回收
const elEventsWeakMap = new WeakMap()
/**最小宽度 */
const MIN_WIDTH = 80
/**最小高度 */
const MIN_HEIGHT = 30
/**触发尺寸 */
const TRIGGER_SIZE = 8
/**触发行列 */
enum RESIZE_CURSOR {
  /**列拉伸 */
  COL_RESIZE = 'col-resize',
  /**行拉伸 */
  ROW_RESIZE = 'row-resize',
}
/**拉伸方向 */
enum POSITION {
  TOP = 'top',
  BOTTOM = 'bottom',
  LEFT = 'left',
  RIGHT = 'right',
}
/**拉伸方向类型 */
type Positions = [POSITION.TOP, POSITION.BOTTOM, POSITION.LEFT, POSITION.RIGHT]
/**拉伸状态 */
interface ResizeState {
  resizing: boolean
  position?: POSITION
  startPointerX?: number
  startPointerY?: number
}
// 表示宽度或高度
type WidthHeight = 'width' | 'height'

// 表示元素的属性
type ElAttr = WidthHeight | 'cursor' | 'display' // 后面补充

// 表示缩放比例
type ResizeFormatter = 'px' | 'flex'
/**接口 */
interface ResizeInfo {
  el: HTMLElement
  positions: Positions
  minWidth: number
  minHeight: number
  triggerSize: number
  formatter: ResizeFormatter
}

interface ResizeOptions {
  el: HTMLElement
  sibling: HTMLElement
  formatter: ResizeFormatter
  elSize: number
  siblingSize: number
  attr?: WidthHeight
}

/**
 * @description: 获取该元素的所有计算后的样式
 * @author: zengxiaolong
 * @Date: 2024-06-03 11:33:41
 * @param {HTMLElement} element
 * @param {ElAttr} attr
 * @return {*}
 */
function getElStyleAttr(element: HTMLElement, attr: ElAttr) {
  // 获取该元素的所有计算后的样式
  const styles = window.getComputedStyle(element)
  return styles[attr]
}

/**
 * @description: 获取元素位置
 * @author: zengxiaolong
 * @Date: 2024-06-03 11:35:15
 * @param {HTMLElement} el
 * @param {POSITION} position
 * @return {*}
 */
function getSiblingByPosition(el: HTMLElement, position: POSITION) {
  const siblingMap = {
    left: el.previousElementSibling,
    right: el.nextElementSibling,
    bottom: el.nextElementSibling,
    top: el.previousElementSibling,
  }
  return siblingMap[position]
}

/**
 * @description: 计算传入元素 el 的所有同级兄弟元素（即兄弟节点）在指定属性（宽度或高度）上的总和。
 * @author: zengxiaolong
 * @Date: 2024-06-03 11:37:57
 * @param {HTMLElement} el 点击的dom节点
 * @param {WidthHeight} attr
 * @return {*}
 */
function getSiblingsSize(el: HTMLElement, attr: WidthHeight) {
  const siblings = (el.parentNode && el.parentNode.children) || []
  return [...siblings].reduce(
    (prev, next) => next.getBoundingClientRect()[attr] + prev,
    0,
  )
}

/**
 * @description: 更新整体尺寸
 * @author: zengxiaolong
 * @param {HTMLElement} el 点击的dom节点
 * @param {HTMLElement} sibling 点击的dom节点移动方向的兄弟节点
 * @param {px/flex} formatter 格式
 * @param {*} elSize 点击的dom节点移动的新尺寸
 * @param {*} siblingSize 点击的dom节点移动方向的兄弟节点的新尺寸
 * @param {width/height} attr 变化属性
 * @Date: 2024-06-03 11:46:49
 * @return {*}
 */
function updateSize({
  el,
  sibling,
  formatter = 'px',
  elSize,
  siblingSize,
  attr = 'width',
}: ResizeOptions) {
  const rowName = $(el).attr('rowName')
  const sibingRowName = $(el).attr('rowName')
  const allRowEl: any[] = [...$(`[rowName='${rowName}']`)]
  const allSibingEl: any[] = [...$(`[rowName='${sibingRowName}']`)]
  if (allRowEl && !allRowEl.length) return
  if (allSibingEl && !allSibingEl.length) return

  let totalSize = elSize + siblingSize
  if (formatter === 'px') {
    // 设置成拉伸的新的尺寸宽度
    allRowEl.forEach((el) => {
      el.style[attr] = elSize + formatter
    })
    allSibingEl.forEach((sibling) => {
      sibling.style[attr] = siblingSize + formatter
    })
  } else if (formatter === 'flex' && attr === 'width') {
    totalSize = getSiblingsSize(el as HTMLElement, attr)
    allRowEl.forEach((el) => {
      el.style.flex = `${(elSize / totalSize) * 10}` // 修复 flex-grow <1
    })
    allSibingEl.forEach((sibling) => {
      sibling.style.flex = `${(siblingSize / totalSize) * 10}`
    })
  } else if (formatter === 'flex' && attr === 'height') {
    // 设置成拉伸的新的尺寸宽度
    ;(el.parentNode as HTMLElement).style[attr] = elSize + 'px'
  }
}

/**
 * @description: 初始化缩放拉伸
 * @author: zengxiaolong
 * @Date: 2024-06-03 11:50:40
 * @return {*}
 */
const initResize = ({
  el,
  positions,
  minWidth = MIN_WIDTH,
  minHeight = MIN_HEIGHT,
  triggerSize = TRIGGER_SIZE,
  formatter = 'px',
}: ResizeInfo) => {
  // 判断dom节点实例为不为空
  if (!el || !(el instanceof HTMLElement)) return
  const resizeState: ResizeState = {
    resizing: false,
  }

  // 获取最初dom节点的cursor样式--为以后按下的鼠标弹起重置回默认值做准备
  const defaultCursor = getElStyleAttr(el, 'cursor')

  // 获取dom节点的样式
  const elStyle = el.style

  // 判断dom节点是否有指令要控制 左 右 上 下 拉伸
  const canLeftResize = positions.includes(POSITION.LEFT)
  const canRightResize = positions.includes(POSITION.RIGHT)
  const canTopResize = positions.includes(POSITION.TOP)
  const canBottomResize = positions.includes(POSITION.BOTTOM)

  // 判断是否制定方向
  if (!canLeftResize && !canRightResize && !canTopResize && !canBottomResize) {
    return
  } // 未指定方向

  // 鼠标移动
  const pointermove = (e: PointerEvent) => {
    // 判断是否正在缩放
    if (resizeState.resizing) return
    // 阻止事件的默认行为
    e.preventDefault()
    // 获取dom节点大小边界
    const { left, right, top, bottom } = el.getBoundingClientRect()
    // 获取鼠标位置
    const { clientX, clientY } = e
    // 左右拉伸
    if (canLeftResize || canRightResize) {
      // 触发区域只能在dom节点容器内部
      if (clientX - left < triggerSize && clientX - left > 0) {
        // 拉伸鼠标位置的距离-dom节点左边位置的距离小于触发的宽度 点击的盒子左侧-左侧竖条拉伸
        resizeState.position = POSITION.LEFT
      } else if (right - clientX < triggerSize && right - clientX > 0) {
        // 拉伸鼠标位置的距离-dom节点右边位置的距离小于触发的宽度 点击的盒子右侧-右侧竖条拉伸
        resizeState.position = POSITION.RIGHT
      } else {
        // 未触发拉伸
        resizeState.position = undefined
      }

      if (resizeState.position === undefined) {
        // 为undefined不进行拉伸
        elStyle.cursor = defaultCursor
      } else {
        // 判断左右兄弟节点
        if (getSiblingByPosition(el, resizeState.position)) {
          elStyle.cursor = RESIZE_CURSOR.COL_RESIZE
        }
        // 阻止事件向上传播
        e.stopPropagation()
      }
    } else if (canTopResize || canBottomResize) {
      // 上下拉伸
      if (clientY - top < triggerSize && clientY - top > 0) {
        // 拉伸鼠标位置的距离-dom节点顶部位置的距离小于触发的宽度 点击的盒子顶侧-顶侧竖条拉伸
        resizeState.position = POSITION.TOP
      } else if (bottom - clientY < triggerSize && bottom - clientY > 0) {
        // 拉伸鼠标位置的距离-dom节点底部位置的距离小于触发的宽度 点击的盒子底侧-底侧竖条拉伸
        resizeState.position = POSITION.BOTTOM
      } else {
        // 未触发拉伸
        resizeState.position = undefined
      }

      if (resizeState.position === undefined) {
        // 为undefined不进行拉伸
        elStyle.cursor = defaultCursor
      } else {
        // 判断上下兄弟节点
        if (getSiblingByPosition(el, resizeState.position)) {
          elStyle.cursor = RESIZE_CURSOR.ROW_RESIZE
        }
        // 阻止事件向上传播
        e.stopPropagation()
      }
    }
  }

  /**
   * @description: 鼠标移开事件
   * @author: zengxiaolong
   * @Date: 2024-06-03 11:51:33
   * @param {PointerEvent} e
   * @return {*}
   */
  const pointerleave = (e: PointerEvent) => {
    // 阻止事件向上传播
    e.stopPropagation()
    // 清除拉伸状态--未拉伸
    resizeState.position = undefined
    // 设置成拉伸后的样式
    elStyle.cursor = defaultCursor
    // 释放指针事件捕获
    el.releasePointerCapture(e.pointerId)
  }

  /**
   * @description: 鼠标按下事件
   * @author: zengxiaolong
   * @Date: 2024-06-03 11:51:33
   * @param {PointerEvent} e
   * @return {*}
   */
  const pointerdown = (e: PointerEvent) => {
    const { resizing, position } = resizeState
    // 判断是否正在拉伸
    if (resizing || !position) return
    // 如果当前节点存在拉伸方向 需要阻止冒泡(用于嵌套拉伸)
    if (position) e.stopPropagation()
    // 开始捕获指针事件
    el.setPointerCapture(e.pointerId)
    // 判断是否有父元素
    if (el.parentElement) {
      // 判断父元素是否设置了 flex
      const isFlex = getElStyleAttr(el.parentElement, 'display') === 'flex'
      if (isFlex) formatter = 'flex'
    }
    // 设置拉伸状态--拉伸中
    resizeState.resizing = true
    // 设置初始拉伸位置
    resizeState.startPointerX = e.clientX
    resizeState.startPointerY = e.clientY

    // 获取dom节点相对于视口的位置
    const { width, height } = el.getBoundingClientRect()

    // 获取dom节点的兄弟节点
    const sibling: HTMLElement = getSiblingByPosition(
      el,
      position,
    ) as HTMLElement
    if (!sibling || !(sibling instanceof HTMLElement)) {
      console.error('未找到兄弟节点', position)
      return
    }

    // 获取dom节点的兄弟节点相对于视口的位置
    const rectSibling = sibling.getBoundingClientRect()

    // 初始拉伸位置
    const { startPointerX, startPointerY } = resizeState

    /**
     * @description: 鼠标移动
     * @author: zengxiaolong
     * @Date: 2024-06-03 11:52:28
     * @param {MouseEvent} e
     * @return {*}
     */
    const onDocumentMouseMove = (e: MouseEvent) => {
      // 是否正在拉伸中
      if (!resizeState.resizing) return
      elStyle.cursor =
        canLeftResize || canRightResize
          ? RESIZE_CURSOR.COL_RESIZE
          : RESIZE_CURSOR.ROW_RESIZE
      // 获取鼠标移动当前位置
      const { clientX, clientY } = e

      // 向左拉伸  或者向右 拉伸
      if (position === POSITION.LEFT || position === POSITION.RIGHT) {
        // 计算鼠标移动的距离--偏移量
        const offsetX = clientX - startPointerX
        // 计算dom节点的新宽度
        const elSize =
          position === POSITION.RIGHT ? width + offsetX : width - offsetX
        // 计算dom节点的兄弟节点新宽度
        const siblingSize =
          position === POSITION.RIGHT
            ? rectSibling.width - offsetX
            : rectSibling.width + offsetX
        // 不能小于dom节点容器的最小宽度
        if (elSize <= minWidth || siblingSize <= minWidth) return

        // 动态更新拉伸后各个容器的大小
        updateSize({ el, sibling, elSize, siblingSize, formatter })
      } else if (position === POSITION.TOP || position === POSITION.BOTTOM) {
        // 向上拉伸  或者向下 拉伸

        // 计算鼠标移动的距离--偏移量
        const offsetY = clientY - startPointerY
        // 计算dom节点的新高度
        const elSize =
          position === POSITION.BOTTOM ? height + offsetY : height - offsetY
        // 计算dom节点的兄弟节点新高度
        const siblingSize =
          position === POSITION.BOTTOM
            ? rectSibling.height - offsetY
            : rectSibling.height + offsetY
        // 不能小于dom节点容器的最小高度
        // if (elSize <= minHeight || siblingSize <= minHeight) return
        if (elSize <= minHeight) return

        // 动态更新拉伸后各个容器的大小
        updateSize({
          el,
          sibling,
          elSize,
          siblingSize,
          formatter,
          attr: 'height',
        })
      }
    }

    /**
     * @description: 鼠标抬起--结束拉伸--移除监听事件
     * @author: zengxiaolong
     * @Date: 2024-06-03 11:52:48
     * @return {*}
     */
    const onDocumentMouseUp = () => {
      // 移除鼠标移动事件监听
      document.removeEventListener('mousemove', onDocumentMouseMove)
      document.removeEventListener('mouseup', onDocumentMouseUp)
      resizeState.resizing = false
      elStyle.cursor = defaultCursor
    }

    // 添加鼠标移动监听事件
    document.addEventListener('mousemove', onDocumentMouseMove)
    document.addEventListener('mouseup', onDocumentMouseUp)
  }

  /**
   * @description: 绑定监听事件
   * @author: zengxiaolong
   * @Date: 2024-06-03 11:53:18
   * @return {*}
   */
  const bindElEvents = () => {
    el.addEventListener('pointermove', pointermove)
    el.addEventListener('pointerleave', pointerleave)
    el.addEventListener('pointerup', pointerleave)
    el.addEventListener('pointerdown', pointerdown)
  }

  /**
   * @description: 解绑监听事件
   * @author: zengxiaolong
   * @Date: 2024-06-03 11:53:29
   * @return {*}
   */
  const unBindElEvents = () => {
    el.removeEventListener('pointermove', pointermove)
    el.removeEventListener('pointerleave', pointerleave)
    el.removeEventListener('pointerup', pointerleave)
    el.removeEventListener('pointerdown', pointerdown)
  }

  bindElEvents()

  // 设置解绑事件
  elEventsWeakMap.set(el, unBindElEvents)
}

/**导出自定义拉伸指令 */
export const resize = {
  // 目前暂时只支持左右拉伸
  bind: function (el: HTMLElement, binding: DirectiveBinding) {
    /**
     * 这种做法有助于防止内存泄漏，因为当组件被销毁时
     * 与组件相关的事件监听器如果不被清除它们可能会继续引用已卸载的组件
     * 导致组件的内存无法被垃圾回收器回收。
     */
    const unBindElEvents = elEventsWeakMap.get(el)
    if (unBindElEvents) unBindElEvents()

    // 例如 v-resize.left.right="[80, 40, 'px']"  modifiers：{ left: true, right: true }
    const { modifiers, value } = binding
    const positions = Object.keys(modifiers)
    initResize({ el, positions, ...value })
  },
}
